import React,{Component} from 'react'
import{
    View,
    Text,
    StyleSheet,
    Dimensions,
    ScrollView,
    ActivityIndicator,
    FlatList,
    Image,
    Alert,
    ToastAndroid,
    Button,
    TextInput,
    TouchableNativeFeedback,
}from 'react-native'

import loading from '../../commons/loading'

const {width,height} =Dimensions.get('window')

const styles=StyleSheet.create({
    input:{
        width:width,
        paddingLeft:10,
        borderBottomWidth:1,
        borderColor:'#ddd',
        paddingRight:10,
        height:50,
        flexDirection:'row',
        justifyContent:'space-between',
        alignItems:'center',
        backgroundColor:'white'
    },
    inputleft:{

    },
    inputright:{
        width:width/2,
    },
    item:{
        width:'100%',
        height:60,
        flexDirection:'row',
        justifyContent:'space-around',
        alignItems:'center',
        backgroundColor:'white'
    },
    singleimg:{
        width:50
    },
    right:{
        width:40,
    },
    jiange:{
        width:'100%',
        borderTopWidth:1,
        borderColor:'rgba(150,150,150,0.2)',
        height:1
    },
    middle:{
        width:200,
        height:'100%',
        flexDirection:'column',
        justifyContent:'space-around',
        alignItems:'center'
    },
    itemwarp:{
        width:'100%',
    },
    other:{
        width:'100%',
        height:40,
        backgroundColor:"white",
        padding:10,
        borderTopWidth:0.5,
        borderColor:'#ddd',
        flexDirection:'row',
        justifyContent:"space-between",
        alignItems:'center'
    },
    other1:{
        width:'100%',
        height:40,
        backgroundColor:"white",
        padding:10,
        borderTopWidth:0.5,
        borderColor:'#ddd',
        flexDirection:'row',
        justifyContent:"space-between",
        alignItems:'center',
        marginBottom:20
    },
        centering: {
        alignItems: 'center',
        justifyContent: 'center',
        padding: 8,
    },
})

const testdata=[1,2,3,4,5,6,7,8]





export default class ToPay extends Component{
    static navigationOptions = {
        title: '下单',
        headerTitleStyle: {
            alignSelf:'center'
          },
      };

      state={
          otherdata:'',
          num:'0',
          tablenum:'0',
          showload:false
      }

    makeorder=async function(){
        try{
        if(this.state.otherdata){
            if(!this.state.num){
                 ToastAndroid.show('请填写用餐人数', ToastAndroid.SHORT);
                 return
            }
            else if(parseInt(this.state.num)!=this.state.num){
                ToastAndroid.show('请填写正确的用餐人数', ToastAndroid.SHORT);
                return
            }
        }
        if(!this.state.tablenum){
                 ToastAndroid.show('请填写桌号', ToastAndroid.SHORT);
                 return
            }
            else if(parseInt(this.state.tablenum)!=this.state.tablenum){
                ToastAndroid.show('请填写正确的桌号', ToastAndroid.SHORT);
                return
            }
        
        var arr=[]
        var total=this.gettotalprice()
        var food=this.props.navigation.state.params.food
        for(var i=0;i<food.length;i++){
            arr.push({
                id: food[i].foodid,
                name: food[i].foodname,
                price: food[i].price,
                nowprice: food[i].price,
                num: food[i].num,
                isrulefood: 0,
                specsid:food[i].id,
                specsname:food[i].listName
            })
        }
        var postdata={
                    totalprice: total,
                    totalnowprice: total,
                    goodsprice:total,
                    phone: global.userdata.id,
                    userid:global.userdata.id,
                    sellerid: global.sellerid,
                    tableno: this.state.tablenum,
                    payType: "3",
                    productlist: arr,
                    youhuilist: [],
                    shAddressId: "",
                    remarks:'',
                    oldOrderId:'',
                    pcount:this.state.num
                }
                this.setState({
                    showload:true
                })
        var response= await fetch(global.mainurl+'/bossHelper/saveOrder', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body:'&orders='+JSON.stringify(postdata)+'&token='+global.token+'&userid='+global.userdata.id
                    })
        console.log(response)
        var result=await response.json()
        if(result.code==1){
            ToastAndroid.show('下单成功', ToastAndroid.SHORT);
            this.setState({
                    showload:false
                })
                this.props.navigation.goBack()
        }
        else{
            ToastAndroid.show(result.msg, ToastAndroid.SHORT);
        }
        }
        catch(error){
            ToastAndroid.show(error, ToastAndroid.SHORT);
        }
    }


     async componentWillMount(){
         console.log(this.props.navigation.state.params.food)
             let response = await fetch(global.mainurl+"bossHelper/getTableware?sellerid="+global.sellerid);
             var result=await response.json()
             console.log(result)
             if(result.code==1&&result.data){
                 this.setState({
                     otherdata:result.data
                 })
             }
             else{
                 return
             }
        }

    gettotalprice=function(){
            var data=0;
            if(this.state.otherdata){
            this.state.otherdata.forEach(indata=>{
                data+=indata.price*this.state.num
            })
            }
            return (parseFloat(this.props.navigation.state.params.totalPrice)+data).toFixed(2)
        }

      render(){
          var otherlist=[]
            for(var i=0;i<this.state.otherdata.length;i++){
                otherlist.push(
                    <View key={i} style={styles.other}>
                    <Text>{this.state.otherdata[i].tablewarename}</Text>
                    <Text>{this.state.otherdata[i].price*this.state.num}</Text> 
                    </View>
                )
            }
          return(
              <ScrollView>
                
                {loading(this.state.showload)}
              <View style={styles.input}>

                <Text style={styles.inputleft}>桌号</Text>
                <TextInput
                placeholder="请输入桌号"
                keyboardType={'numeric'}
                onChangeText={(text)=>{
                            this.setState({
                                tablenum:text
                            })
                        }}
                style={styles.inputright}
                />
              </View>
              {
                  this.state.otherdata
                  ?
                  <View style={styles.input}>
                    <Text style={styles.inputleft}>就餐人数</Text>
                    <TextInput
                    placeholder="请输入就餐人数"
                    keyboardType={'numeric'}
                    style={styles.inputright}
                    onChangeText={(text)=>{
                            this.setState({
                                num:text
                            })
                        }}
                    />
                  </View>
                  :
                  <Text></Text>
              }
              <View style={styles.itemwarp}>
              <FlatList
                data={this.props.navigation.state.params.food}
                ItemSeparatorComponent={()=>{
                        return(
                            <View style={styles.jiange}/>
                            )
                        
                    }}
                keyExtractor={(item, index) => index}
                renderItem={
                    (item)=>{
                        return(
                        <View style={styles.item}>
                            <Image
                            source={{uri:global.imgurl+item.item.src}}
                            style={styles.singleimg}
                            resizeMode='contain'
                            />
                            <View style={styles.middle}>
                            <Text>{item.item.foodname+item.item.listName}</Text>
                            <Text>X{item.item.num}</Text>
                            </View>
                            <Text  style={styles.right}>
                            {item.item.price}
                            </Text>
                        </View>
                        )
                    }
                }
              />
              </View>
              {otherlist}
              <View style={styles.other1}>
                <Text>总金额</Text>
                <Text>{this.gettotalprice()}</Text>
              </View>
                <Button
                    onPress={()=>{
                                    Alert.alert(
                                        '确定完成支付？',
                                        null,
                                        [
                                        {text: '取消', onPress: () => {}},
                                        {text: '确定', onPress: () => this.makeorder()},
                                        {text: '', onPress: () =>{} },
                                        ]
                                    )
                                    
                                }}
                    title="确认下单"
                    style={{padding:20,marginBottom:20}}
                    color="#841584"
                />
                <Text style={{marginBottom:20}}></Text>
                
              </ScrollView>
          )
      }
}